'use strict';

const Controller = require('egg').Controller;
const utility = require('utility');
const path = require('path');
const fs = require('fs');
const {
  MISS_PARAM,
  SUCCESS,
  UPLOAD_FILE_ERROR,
  EXT_NOT_RIGHT,
  DOWNLOAD_FILE,
} = require('../constant/index');

class FileController extends Controller {
  async listFile() {
    this.ctx.body = '文件添加成功';
  }

  async uploadFile() {
    // 数据库中存储的文件名，用户查询和删除用的
    const name = utility.md5(`${Date.now}${Math.floor(Math.random() * 1000)}`);
    // 获取上传的文件
    let file = '';
    try {
      file = await this.ctx.getFileStream();
    } catch (error) {
      this.ctx.body = {
        code: EXT_NOT_RIGHT,
        message: '文件扩展名不合法或文件大小超过限制',
      };
      return;
    }
    // 开始上传文件
    let result = '';
    try {
      result = await this.ctx.service.file.uploadFile(file, name);
    } catch (error) {
      this.ctx.body = {
        code: UPLOAD_FILE_ERROR,
        message: '文件上传失败',
      };
      return;
    }
    // 获取文件名
    const fileName = file.filename || '';
    // 开始像数据库中写文件路径
    await this.ctx.service.file.addNewFile({
      name: fileName.split('.')[0] || '',
      ext: fileName.split('.')[1] || '',
      size: 0,
      path: result.path,
    }, name);
    this.ctx.body = {
      code: SUCCESS,
      message: '上传成功',
    };
  }

  /**
   * 下载文件
   */
  async downloadFile() {
    const { name } = this.ctx.params;
    // 如果当前传入商品
    if (!name) {
      this.ctx.body = {
        code: MISS_PARAM,
        message: '下载文件失败',
      };
      return;
    }
    try {
      const filePath = path.join(this.config.filePath, name);
      this.ctx.body = fs.readFileSync(filePath);
    } catch (err) {
      this.ctx.body = {
        code: DOWNLOAD_FILE,
        message: '下载文件失败',
      };
    }
  }

  async addDirectory() {
    // 获取请求参数
    const query = this.ctx.request.body;
    // 如果文件夹名称没有输入，则不处理
    if (!query.name) {
      this.ctx.body = {
        code: MISS_PARAM,
        message: '请输入文件夹名称',
      };
      return;
    }
    this.ctx.body = {
      code: SUCCESS,
      message: '新建成功',
    };
  }

  async deleteDirectory() {
    const query = this.ctx.query;
    this.ctx.body = query;
  }

  async updateDirectory() {
    const query = this.ctx.request.body;
    this.ctx.body = query;
  }
}

module.exports = FileController;
